//
//  CJAddFirmProductController.m
//  Boss
//
//  Created by admin on 2018/9/17.
//  Copyright © 2018年 admin. All rights reserved.
//

#import "CJAddFirmProductController.h"
#import "CJAddProductImageCell.h"
#import "CJAddProductHeaderCell.h"
#import "CJAddProductImageCell.h"
#import "WYUploadModel.h"
#import "UIImage+WYSaveImage.h"
@interface CJAddFirmProductController ()<UITableViewDelegate,UITableViewDataSource,CJAddProductImageCellDelegate,CJAddProductHeaderCellDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSString *pathString;

@property (nonatomic,strong)WYUploadModel *uploadNodel;

@property (nonatomic,strong)NSMutableArray *urlArray;

@property (nonatomic,strong)NSString *productCoverString;
@property (nonatomic,assign)NSUInteger index;

@property (nonatomic,strong)NSMutableArray *imageArray;

@property (nonatomic,strong)CJAddProductHeaderCell *headerCell;
@property (nonatomic,strong)CJAddProductImageCell *imageCell;
@property (nonatomic,strong)UIImage *photoImage;
@end

@implementation CJAddFirmProductController

-(NSMutableArray *)imageArray
{
    if (!_imageArray) {
        _imageArray = [[NSMutableArray alloc]init];
    }
    return _imageArray;
}

-(NSMutableArray *)urlArray
{
    if (!_urlArray) {
        _urlArray  = [[NSMutableArray alloc]init];
    }
    return _urlArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    // Do any additional setup after loading the view.
}
-(void)setupUI
{
    self.navigationItem.title = @"发布产品";
    [self.view addSubview:self.tableView];
    [self.tableView registerNib:[UINib nibWithNibName:@"CJAddProductHeaderCell" bundle:nil] forCellReuseIdentifier:@"CJAddProductHeaderCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"CJAddProductImageCell" bundle:nil] forCellReuseIdentifier:@"CJAddProductImageCell"];
    self.tableView.estimatedRowHeight = 100;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:(UIBarButtonItemStyleDone) target:self action:@selector(saveAction)];
    if (self.model) {
        self.urlArray = [self.model.url componentsSeparatedByString:@","].mutableCopy;
        
        self.productCoverString = self.model.productCover;
            // UI更新代码
        [self.headerCell.productOvcerImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@!default",self.model.productCover]]];
        self.headerCell.textField.text = self.model.productName;
        self.imageCell.textField.text = self.model.productDetails;
        
    }
    
    
}

-(void)saveAction
{
    if (!self.productCoverString.length) {
        [self toast:@"请添加产品封面图"];return;
    }
    if (!self.headerCell.textField.text.length) {
        [self toast:@"请输入产品名称"];return;
    }
    if (!self.imageCell.textField.text.length) {
        [self toast:@"请输入产品介绍"]; return;
    }
    NSString *urlString;
    if (!self.urlArray.count) {
        [self toast:@"请添加产品图片"];return;
    }
    urlString = [self.urlArray componentsJoinedByString:@","];
    
    WEAKSELF
    [WYHttpServer insertFirmProductWithUrl:urlString WithProductName:self.headerCell.textField.text WithProductCover:self.productCoverString WithProductId:self.model.id WithProductDetails:self.imageCell.textField.text SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
       
        if (success) {
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [self toast:errorMessage];
                
            });
        }
        
        
        
        
        
        
        
    }];
    
    
    
    
    
}





-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        CJAddProductHeaderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CJAddProductHeaderCell" forIndexPath:indexPath];
        if (!cell) {
            cell = [[NSBundle mainBundle]loadNibNamed:@"CJAddProductHeaderCell" owner:nil options:nil].firstObject;
        }
        self.headerCell = cell;
        cell.delegate = self;
        if (self.model) {
           [cell.productOvcerImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@!default",self.model.productCover]]];
            cell.textField.text = self.model.productName;
        }
        
        
        
        cell.selectionStyle  = UITableViewCellSelectionStyleNone;
        return cell;
    }
    if (indexPath.row==1) {
        CJAddProductImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CJAddProductImageCell" forIndexPath:indexPath];
        if (!cell) {
            cell = [[NSBundle mainBundle]loadNibNamed:@"CJAddProductImageCell" owner:nil options:nil].firstObject;
        }
        self.imageCell = cell;
        [cell setDataArray:self.urlArray];
        cell.delegate = self;
        if (self.model) {
            cell.textField.text = self.model.productDetails;
        }
        
        cell.selectionStyle  = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
    return nil;
}

-(void)didChangeHeight:(CJAddProductImageCell *)productCell
{
    dispatch_async(dispatch_get_main_queue(), ^{
        // UI更新代码
        [self.tableView reloadData];
        NSIndexPath *indexPath = [self.tableView indexPathForCell:productCell];
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionNone animated:NO];

    });
    
    
    
    // [cell.inputView becomeFirstResponder];
}
-(void)deleteImageClick:(NSUInteger)tag
{
    [self.urlArray removeObjectAtIndex:tag];
    [self.imageCell setDataArray:self.urlArray];
}
#pragma mark CJAddProductHeaderCellDelegate
-(void)addProductOverImage
{
    self.index = 0;
    [self showPicker];
}


-(void)addProductImageView
{
    self.index=1;
    
    [self showPicker];
}


-(void)addProductImage
{
    self.index = 0;
    [self showPicker];
}

-(void)showPicker
{
    WEAKSELF
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self; //设置代理
    imagePickerController.allowsEditing = YES;
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [weakSelf presentViewController:imagePickerController animated:YES completion:nil];
    }];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [weakSelf presentViewController:imagePickerController animated:YES completion:nil];
    }];
    [alertController addAction:action1];
    [alertController addAction:action2];
    [alertController addAction:action3];
    if (IS_IPAD) {
        //        UIPopoverPresentationController *popPresenter = [alertController popoverPresentationController];
        //        popPresenter.sourceView = cell;
        //        popPresenter.sourceRect = cell.bounds;
        //        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{}];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    //[self showLoading:@""];
    [picker dismissViewControllerAnimated:YES completion:^{}];
    UIImage *photo = [info objectForKey:UIImagePickerControllerOriginalImage];
    self.photoImage = photo;
    NSString *path = [photo QCloudTempFilePathWithExtension:@"PNG"];
    self.pathString = path;
    [UIImagePNGRepresentation(photo) writeToFile:path atomically:YES];
    
    [self showLoading:@""];
    
    WEAKSELF
    [WYHttpServer uploadImageSucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        WYUploadModel *model = [WYUploadModel getupLoadModelFromJson:response[@"result"]];
        [weakSelf upLoadWithPath:model.uploadUrl];
        weakSelf.uploadNodel = model;
    }];
}
-(void)upLoadWithPath:(NSString *)path
{
    WEAKSELF
    [WYHttpServer PUTWithURLStr:path filePath:self.pathString SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        dispatch_async(dispatch_get_main_queue(), ^{
            // UI更新代码
            [weakSelf hideLoading];
        });
        if (success) {
            if (self.index ==0) {
                weakSelf.productCoverString = self.uploadNodel.visitUrl;
               
                dispatch_async(dispatch_get_main_queue(), ^{
                    // UI更新代码
                     weakSelf.headerCell.productOvcerImage.image = self.photoImage;
                });
                
                
            }else{
                [weakSelf.urlArray addObject:self.uploadNodel.visitUrl];
                [weakSelf.imageCell setDataArray:weakSelf.urlArray];
            }
        }else{
            [weakSelf toast:errorMessage];
        }
    }];
}













- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


- (UITableView *)tableView
{
    if (_tableView == nil) {
        CGRect frame = CGRectMake(0, self.navHeight, kScreenWidth, kScreenHeight-self.navHeight);
        _tableView = [[UITableView alloc] initWithFrame:frame
                                                  style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView setSeparatorStyle:(UITableViewCellSeparatorStyleNone)];
    }
    return _tableView;
}









@end
